import React, { forwardRef, useEffect, useImperativeHandle, useState } from 'react';
import { Space } from 'antd';
import { getCode } from '@/services/system/login';
import styles from './style.module.less';
import { SafetyCertificateOutlined } from '@ant-design/icons';
import { ProFormText } from '@ant-design/pro-components';

const timeout = 1000 * 60 * 5;

export interface CaptchaInputRef {
  getCaptchaKey: () => string;
  onClickImage: () => void;
}

const MyCaptchaInput = forwardRef<CaptchaInputRef>((_, ref) => {
  const [captchaKey, setCaptchaKey] = useState<string>('');
  const [imageData, setImageData] = useState<string | undefined>();
  const [val, setVal] = useState<string>('');
  const [intervalId, setIntervalId] = useState<NodeJS.Timeout>();
  // // 输入框变化
  const onChangeInput = (e: React.ChangeEvent<HTMLInputElement>) => {
    setVal(e.target.value || '');
  };

  // 图片变化
  const onClickImage = () => {
    if (intervalId) clearTimeout(intervalId);
    const timer = setTimeout(onClickImage, timeout);
    setIntervalId(timer);
    getCode().then((res: any) => {
      setCaptchaKey(res.data.key);
      setImageData(res.data.base64);
      setVal('');
    });
  };

  const getCaptchaKey = () => captchaKey;

  // 使用 useImperativeHandle 来暴露 checkCode 方法
  useImperativeHandle(ref, () => ({
    getCaptchaKey,
    onClickImage,
  }));

  useEffect(() => {
    onClickImage();
    return () => clearTimeout(intervalId);
  }, []);

  return (
    <Space.Compact block>
      <div className={styles.captchaInput}>
        <ProFormText
          name="code"
          fieldProps={{
            size: 'large',
            prefix: <SafetyCertificateOutlined />,
            value: val,
            onChange: onChangeInput,
          }}
          placeholder="验证码"
          rules={[
            {
              required: true,
              message: '请输入验证码!',
            },
          ]}
        />
      </div>
      <img
        className="w-[25%] h-[40px] p-0 rounded-[8px]"
        src={imageData}
        onClick={onClickImage}
        alt="验证码"
      />
    </Space.Compact>
  );
});

export default MyCaptchaInput;
